<template>
  <div class="user-container">
    <div class="search-container" style="display: flex; align-items: center; justify-content: space-between;">
      <el-button type="success" @click="handleAdd" class="add-btn">
        <el-icon>
          <Plus />
        </el-icon>添加用户
      </el-button>

      <div style="display: flex; align-items: center;">
        <el-input v-model="searchQuery" placeholder="请输入用户名搜索" class="search-input" clearable
          @clear="getUserList" @keyup.enter="getUserList" style="width: 300px; margin-right: 10px;">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="info" @click="getUserList" class="search-btn" style="margin-right: 10px;">
          <el-icon>
            <Search />
          </el-icon>搜索
        </el-button>
        <el-button type="danger" @click="handleClear" class="clear-btn">
          <el-icon>
            <Delete />
          </el-icon>清除
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="userList" class="custom-table" :header-cell-style="{
      background: '#f6f8f9',
      color: '#606266',
      fontWeight: '500',
      fontSize: '14px'
    }" :cell-style="{
        padding: '12px 0',
        fontSize: '14px',
        color: '#606266'
      }" :row-style="{
        height: '60px',
        transition: 'background-color 0.3s'
      }" border stripe highlight-current-row>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-image :src="`/api/Userfile/${scope.row.avatar}`" :preview-src-list="[`/api/Userfile/${scope.row.avatar}`]"
            class="avatar-img" fit="cover" :hide-on-click-modal="false" preview-teleported>
            <template #error>
              <el-icon style="font-size: 16px">
                <User />
              </el-icon>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="username" min-width="120" align="center" />
      <el-table-column label="姓名" prop="name" min-width="120" align="center" />
      <el-table-column label="密码" prop="password" min-width="120" align="center" show-overflow-tooltip />
      <el-table-column label="创建时间" prop="created_at" min-width="180" align="center" />
      <el-table-column label="更新时间" prop="updated_at" min-width="180" align="center" />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="scope">
          <div style="display: flex; justify-content: center; gap: 10px;">
            <el-button type="success" size="small" @click="handleEdit(scope.row)" class="edit-btn">
              <el-icon>
                <Edit />
              </el-icon>编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="delete-btn">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" background class="custom-pagination" />
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog :title="dialogType === 'add' ? '添加用户' : '编辑用户'" v-model="dialogVisible" width="500px"
      :close-on-click-modal="false" destroy-on-close class="user-dialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="user-form">
        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" action="/api/Userfile/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="uploadHeaders"
            :on-error="handleAvatarError">
            <template v-if="form.avatar">
              <img :src="`/api/Userfile/${form.avatar}`" class="avatar" />
            </template>
            <template v-else>
              <el-icon class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" class="form-input" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" class="form-input" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" class="form-input" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleSubmit" class="submit-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, User } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const userList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')

// 表单相关
const formRef = ref(null)
const form = reactive({
  username: '',
  password: '',
  name: '',
  avatar: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 上传相关配置
const uploadHeaders = {
  Authorization: localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await request.get('/users/search', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        username: searchQuery.value || undefined
      }
    })
    if (res.code === 200 && res.data) {
      userList.value = res.data.list
      total.value = res.data.total
      
      if (userList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        await getUserList()
        return
      }
    } else {
      userList.value = []
      total.value = 0
      ElMessage.warning('未找到相关数据')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    userList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    form.avatar = response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const handleAvatarError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('图片上传失败')
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  form.username = ''
  form.password = ''
  form.name = ''
  form.avatar = ''
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/users/addadmin', {
        ...form,
        type: dialogType.value
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
          dialogVisible.value = false
          currentPage.value = 1
          getUserList()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      }).catch(error => {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      })
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    request.delete('/users/delete', {
      data: { id: row.id }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getUserList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    }).catch(error => {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    })
  })
}

// 添加清除功能
const handleClear = () => {
  searchQuery.value = ''
  currentPage.value = 1
  getUserList()
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
}

.add-btn {
  background-color: #2f3447;
  border-color: #2f3447;
  color: #fff;
}

.add-btn:hover {
  background-color: #383d52;
  border-color: #383d52;
}

.search-btn {
  background-color: #f9dee1;
  border-color: #f9dee1;
  color: #2f3447;
}

.search-btn:hover {
  background-color: #f5c5cb;
  border-color: #f5c5cb;
}

.clear-btn {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.clear-btn:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  margin: 20px 0;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f9dee1 !important;
}

.avatar-img {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid #f9dee1;
  transition: all 0.3s;
}

.avatar-img:hover {
  transform: scale(1.1);
  border-color: #2f3447;
}

.edit-btn {
  background-color: #2f3447;
  border-color: #2f3447;
}

.edit-btn:hover {
  background-color: #383d52;
  border-color: #383d52;
}

.delete-btn {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.delete-btn:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.custom-pagination :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #2f3447;
}

.avatar-uploader {
  border: 2px dashed #f9dee1;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.avatar-uploader:hover {
  border-color: #2f3447;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.form-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  background-color: #f9dee1;
  border-color: #f9dee1;
  color: #2f3447;
}

.cancel-btn:hover {
  background-color: #f5c5cb;
  border-color: #f5c5cb;
}

.submit-btn {
  background-color: #2f3447;
  border-color: #2f3447;
}

.submit-btn:hover {
  background-color: #383d52;
  border-color: #383d52;
}
</style>